import {
  Component,
  ChangeDetectionStrategy,
  OnInit, OnDestroy, ViewEncapsulation, ChangeDetectorRef,
} from '@angular/core';
import { ApiService } from '@core/services/http/api.service';
import { ApesMessageService } from '@shared/apes/message';
import { FormBuilder, FormControl, FormGroup, Validators } from '@angular/forms';
import * as CryptoJS from 'crypto-js';
import { UserAuthService } from '@core/services/user-auth.service';
import { Router } from '@angular/router';
import { ReuseTabService } from '@shared/apes/reuse-tab';

@Component({
  selector: 'app-account-settings-base',
  templateUrl: './base.component.html',
  styleUrls: ['./base.component.scss'],
  encapsulation: ViewEncapsulation.None,
})
export class ProAccountSettingsBaseComponent implements OnInit, OnDestroy {

  form: FormGroup;
  count = 0;
  interval$: any;
  _mobile: any = '';
  _origin: any = '';

  passwordVisible = false;
  checkPasswordVisible = false;
  mobileNumber: boolean = true;

  constructor(fb: FormBuilder,
              private api: ApiService,
              private msg: ApesMessageService,
              private userAuthService: UserAuthService,
              private router: Router,
              private reuseTabService: ReuseTabService,
              private cd: ChangeDetectorRef,
  ) {
    this.form = fb.group({
      password: ['', [Validators.required, Validators.minLength(6),Validators.pattern(/^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{6,16}$/)]],        // 123456
      checkPassword: ['', [Validators.required, this.confirmationValidator]],
      mobile: [null, [Validators.required, Validators.pattern(/^1\d{10}$/)]],
      captcha: [null, [Validators.required]],
    });

  }

  ngOnInit() {
    let userInfo = this.userAuthService.getUserInfoObj();
    this._mobile = userInfo.userAccount['mobileNumber'];
    this._origin = userInfo.userAccount['origin'];
  }

  get password() {
    return this.form.controls.password;
  }

  get checkPassword() {
    return this.form.controls.checkPassword;
  }

  get mobile() {
    return this.form.controls.mobile;
  }

  get captcha() {
    return this.form.controls.captcha;
  }

  confirmationValidator = (control: FormControl): { [s: string]: boolean } => {
    if (!control.value) {
      return { required: true };
    } else if (control.value !== this.form.controls.password.value) {
      return { confirm: true, error: true };
    }
    return {};
  };

  // 获取验证码
  getCaptcha() {
    this.count = 59;
    if (!this.mobile.value) {
      return;
    }
    const userModel = { phone: this.mobile.value };
    this.api.post('aut.user.getCaptchaApp', { 'body': JSON.stringify(userModel) }).subscribe(
      (body) => {
        if (body) {
        } else {
          // this.msg.error('验证码发送不正确');
        }
      });
    this.interval$ = setInterval(() => {
      this.count -= 1;
      this.cd.markForCheck();
      if (this.count <= 0)
        clearInterval(this.interval$);
    }, 1000);
  }

  mobileChanges(e) {
    e.length === 11 ? this.mobileNumber = false : this.mobileNumber = true;
  }

  check() {
    this.password.markAsDirty();
    this.checkPassword.markAsDirty();
    this.mobile.markAsDirty();
    this.captcha.markAsDirty();

    let result = true;
    if (!this.password.value) {
      this.msg.error('密码不正确');
      result = false;
      return result;
    }
    if (!this.checkPassword.value) {
      this.msg.error('确认密码不正确');
      result = false;
      return result;
    }
    if (!this.mobile.value) {
      this.msg.error('手机号不正确');
      result = false;
      return result;
    }
    if (!this.captcha.value) {
      this.msg.error('验证码不正确');
      result = false;
      return result;
    }
    return result;
  }

  changePassword() {
    if (!this.check()) {
      return;
    }

    const data = {
      password: CryptoJS.MD5(this.password.value).toString(),
      captcha: this.captcha.value,
      origin: this._origin,
      phone: this.mobile.value,
    };
    let platform = this.userAuthService.getUserInfoObj() ? this.userAuthService.getUserInfoObj().platform : '';

    this.api.post('aut.user.updatePasswordNew', { 'body': JSON.stringify(data) }).subscribe((body) => {
      if (body) {
        this.msg.success('密码修改成功，请重新登录');
        this.userAuthService.removeUserInfo();
        if (platform === 'fn' || platform == 'gys') {
          this.router.navigateByUrl('/empower/login');
        } else if (platform === 'zt') {
          this.router.navigateByUrl('/headquarters/login');
        } else {
          this.router.navigateByUrl('/passport/login');
        }

        // 清除复用路由导航
        // this.reuseTabService.clear();
      }
    });
  }

  ngOnDestroy(): void {
    if (this.interval$) {
      clearInterval(this.interval$);
    }
  }

}
